<template>
  <div class="app-container">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="选择表单" >
            <el-tree-select v-model="formData.formId" 
                          placeholder="选择表单"
                          :data="selectTreeNodes" 
                           default-expand-all
                          :props="{ children: 'list', value: 'id', label: 'name', disabled: (data,node) => data.nodeType == 1 }" 
                          />
        </el-form-item>
    </el-form>
    <el-col :span="6">
        <el-button style="float:right;" size="mini" type="primary" @click="handleSubmit">保存</el-button>
    </el-col>
  </div>
</template>

<script setup lang="ts">
    import { reactive, ref, watch, toRefs, onMounted,nextTick} from 'vue'
    import { ElForm, ElMessage } from 'element-plus';
    //事件总线
    import emitter from '@/utils/bus' 
     /*****请求组件引入****/
    import { addAppMenuNode} from '@/api/appMenu';
    import { formTree } from '@/api/form';
    import { saveAppView, getAppView } from '@/api/appView'

     /****关联组件*****/
    const formRef = ref(ElForm); // 属性名必须和元素的ref属性值一致

    const state = reactive({
      formData: {},
      selectTreeNodes:[]
    });
    const {
      formData,
      selectTreeNodes
    } = toRefs(state);

    const parentData = defineProps({
        props: {
          id: String
        }
    });

    
    watch(() => parentData.props.id,
       // 回调函数 callback
       (newValue, oldValue) => {
         nextTick(() =>{
              showViewPage(newValue);
         })
        
       }, {immediate:true,deep: true}
    );
    
    function showViewPage(appMenuId: String){
         getAppView(appMenuId).then(response =>{
            console.log(response.data);
            if(response.data && response.data.formId){
                state.formData.formId = response.data.formId;
            }else{
                state.formData.formId = null;
            }
            emitter.emit('appMenu_formId', state.formData.formId);
         });
    }

    formTree().then(response => {
        state.selectTreeNodes = response.data;
    });

    function treeDisabled(data,node){ return data.nodeType == 1 }

    const handleSubmit = (callName) => {
       formRef.value.validate((valid: boolean) => {
        if (valid) {
          state.formData.appMenuId=parentData.props.id;
          saveAppView(state.formData).then(response =>{
             emitter.emit('appMenu_formId', state.formData.formId);
             ElMessage.success('保存成功');
          });
        } else {
          return false;
        }
      }); 
    }
</script>

<style lang="scss" scoped></style>